登录 白背景

384. 打乱数组

https://leetcode-cn.com/problems/shuffle-an-array/

  • 提交时间:2021-11-22 15:44:01
  • 执行用时:40 ms, 在所有 Go 提交中击败了77.27%的用户
  • 内存消耗:9.1 MB, 在所有 Go 提交中击败了64.01%的用户
  • 通过测试用例:10 / 10
type Solution struct {
    n          int
    numsOrigin []int
    nums       []int
}

func Constructor(nums []int) Solution {
    return Solution{numsOrigin: nums, nums: append([]int(nil), nums...), n: len(nums)}
}

func (t *Solution) Reset() []int {
    copy(t.nums, t.numsOrigin)
    return t.nums
}

func (t *Solution) Shuffle() []int {
    //洗牌算法
    for i := 0; i < t.n-1; i++ {
        randI := i + rand.Intn(t.n-i)
        t.nums[i], t.nums[randI] = t.nums[randI], t.nums[i]
    }
    return t.nums
}


/**
 * Your Solution object will be instantiated and called as such:
 * obj := Constructor(nums);
 * param_1 := obj.Reset();
 * param_2 := obj.Shuffle();
 */